<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>ServeMux、httprouter | J.のblog</title><meta name="keywords" content="云原生,golang"><meta name="author" content="J."><meta name="copyright" content="J."><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="description" content="ServeMux、httprouter一、创建一个简单的goWeb服务器func Hello(w http.ResponseWriter, r *http.Request) &amp;#123;     fmt.Println(&quot;1&quot;, r.RemoteAddr)     fmt.Println(&quot;2&quot;, r.Method)     fmt.Println(&quot;3&quot;, r.Host)     fmt.Pri">
<meta property="og:type" content="article">
<meta property="og:title" content="ServeMux、httprouter">
<meta property="og:url" content="http://dycloudnavite.love/2023/06/04/ServeMux%E3%80%81httprouter/index.html">
<meta property="og:site_name" content="J.のblog">
<meta property="og:description" content="ServeMux、httprouter一、创建一个简单的goWeb服务器func Hello(w http.ResponseWriter, r *http.Request) &amp;#123;     fmt.Println(&quot;1&quot;, r.RemoteAddr)     fmt.Println(&quot;2&quot;, r.Method)     fmt.Println(&quot;3&quot;, r.Host)     fmt.Pri">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://dycloudnavite.love/img/golang.png">
<meta property="article:published_time" content="2023-06-04T03:32:00.000Z">
<meta property="article:modified_time" content="2023-08-30T03:09:18.790Z">
<meta property="article:author" content="J.">
<meta property="article:tag" content="云原生">
<meta property="article:tag" content="golang">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://dycloudnavite.love/img/golang.png"><link rel="shortcut icon" href="/dujie5416/img/touxiang.png"><link rel="canonical" href="http://dycloudnavite.love/2023/06/04/ServeMux%E3%80%81httprouter/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/dujie5416/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/dujie5416/',
  algolia: {"appId":"9GWB2VV7GN","apiKey":"dac56ec5b0b1f45281251ee59db4d637","indexName":"blog","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'ServeMux、httprouter',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-08-30 11:09:18'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/xxx.css"><link rel="stylesheet" href="/css/universe.css"><link rel="stylesheet" href="/css/custom.css"><style type="text/css">#toggle-sidebar {bottom: 80px}</style><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/tzy13755126023/BLOG_SOURCE/css/function.min.css"><link rel="stylesheet" href="/css/rightMenu.css"><style type="text/css">#toggle-sidebar {left:100px}</style><!-- hexo injector head_end start --><link rel="stylesheet" href="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.css" /><!-- hexo injector head_end end --><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/dujie5416/atom.xml" title="J.のblog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/dujie5416/img/touxiang.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/dujie5416/img/longzhu.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/dujie5416/">J.のblog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/dujie5416/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/dujie5416/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">ServeMux、httprouter</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-08-30T03:09:18.790Z" title="更新于 2023-08-30 11:09:18">2023-08-30</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/dujie5416/categories/golang/">golang</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="ServeMux、httprouter"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="ServeMux、httprouter"><a href="#ServeMux、httprouter" class="headerlink" title="ServeMux、httprouter"></a>ServeMux、httprouter</h1><h3 id="一、创建一个简单的goWeb服务器"><a href="#一、创建一个简单的goWeb服务器" class="headerlink" title="一、创建一个简单的goWeb服务器"></a>一、创建一个简单的goWeb服务器</h3><pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Hello</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"1"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>RemoteAddr<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"2"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Method<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"3"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Host<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"4"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>URL<span class="token punctuation">)</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"这是测试页面"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    http<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> Hello<span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">:=</span> http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">":8080"</span><span class="token punctuation">,</span><span class="token boolean">nil</span><span class="token punctuation">)</span><span class="token punctuation">;</span>err<span class="token operator">!=</span><span class="token boolean">nil</span><span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上例代码，main()函数通过代码<code>http.ListenAndServe(&quot;:8080&quot;,nil)</code> 启动一个8080 端口的服务器。如果这个函数传入第一个参数(网络地址)为空，则服务器在启动后默认使用 <a target="_blank" rel="noopener" href="http://127.0.0.1:8080/">http://127.0.0.1:8080</a> 地址进行访问；如果这个函数传入的第二个参数为nil，则服务器在启动后将使用<strong>默认的多路复用器(DefaultServeMux)</strong></p>
<p>运行上例代码，在浏览器中访问<a href="http://127.0.0.1:8080%EF%BC%8C%E9%BB%98%E8%AE%A4%E4%BC%9A%E6%98%BE%E7%A4%BA/">http://127.0.0.1:8080，默认会显示</a> “这是测试页面”字符串</p>
<p><img src="/images/hIeiHevWkLJZiTON48hDf12pL6vr4fRGnCp20P0Utls.png" alt="image"></p>
<p>用户可以通过Server结构体对服务器进行更加详细的配置，包括为请求读取操作设置超时时间等。GoWeb服务器的请求和响应流程如下：</p>
<p><img src="/images/12cHr9ikXtyQXMGMLAsneQmfz5lpgER4HJ8TZ6WRzfk.png" alt="image"></p>
<ol>
<li>客户端发送请求；</li>
<li>服务器端的多路复用器收到请求；</li>
<li>多路复用器请求的URL找到注册的处理器，将请求交由处理器处理</li>
<li>处理器执行程序逻辑，如果必要，则与数据库进行交互，得到处理结果</li>
<li>处理器调用模板引擎将指定的模板和上一步得到的结果渲染成客户端可识别的数据格式（通常是HTML）</li>
<li>服务器端将数据通过HTTP相应返回给客户端。</li>
<li>客户端拿到数据，执行对应的操作（例如渲染出来呈现给用户）</li>
</ol>
<h3 id="二、接受请求"><a href="#二、接受请求" class="headerlink" title="二、接受请求"></a><strong>二、接受请求</strong></h3><h5 id="2-1、ServeMux和DefaultServeMux"><a href="#2-1、ServeMux和DefaultServeMux" class="headerlink" title="2.1、ServeMux和DefaultServeMux"></a><strong>2.1、ServeMux和DefaultServeMux</strong></h5><p>####### <strong>1、ServeMux和DefaultServeMux简介</strong><br><img src="/images/c0wZVZywXOppPf_EakxP_EqF14PsEzNpA9kXDIHvnXU.png" alt="image"></p>
<p>ServeMux 是一个结构体，其中包括一个映射，这个映射将会URL映射至相应的处理器。它会在映射中找出与被请求URL最为匹配的URL，然后调用与之相对应的处理器<code>ServeHTTP()</code>方法来处理请求</p>
<p>DefaultServeMux 是 net&#x2F;http 包中默认提供的一个多路复用器，其本质是ServeMux的一个实例。多路服务器的任务是——根据请求的URL将请求重定向到不同的处理器。如果用户没有为Serve对象指定处理器，则服务器默认使用DefaultServeMux作为ServeMux结构体的实例。</p>
<p><code>HandleFunc()</code> 函数用于为指定的URL注册一个处理器。<code>HandleFunc()</code> 处理器函数会在内部调用DefaultServeMux对象的对应方法，其内部实现如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">HandleFunc</span><span class="token punctuation">(</span>pattern <span class="token builtin">string</span><span class="token punctuation">,</span> handler <span class="token keyword">func</span><span class="token punctuation">(</span>ResponseWriter<span class="token punctuation">,</span> <span class="token operator">*</span>Request<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	DefaultServeMux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span>pattern<span class="token punctuation">,</span> handler<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>上面的方法可以看出，<code>http.HandleFunc()</code> 函数将处理器注册到多路复用器中。用默认多路复用器还可以指定多个处理器，其使用方法如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// The HandlerFunc type is an adapter to allow the use of</span>
<span class="token comment">// ordinary functions as HTTP handlers. If f is a function</span>
<span class="token comment">// with the appropriate signature, HandlerFunc(f) is a</span>
<span class="token comment">// Handler that calls f.</span>
<span class="token keyword">type</span> HandlerFunc <span class="token keyword">func</span><span class="token punctuation">(</span>ResponseWriter<span class="token punctuation">,</span> <span class="token operator">*</span>Request<span class="token punctuation">)</span>

<span class="token comment">// ServeHTTP calls f(w, r).</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>f HandlerFunc<span class="token punctuation">)</span> <span class="token function">ServeHTTP</span><span class="token punctuation">(</span>w ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token function">f</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> r<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>下面的代码中，自定义了两个Handle，都实现了http.Handler接口，因为他们都实现了ServeHTTP方法</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"fmt"</span>
    <span class="token string">"net/http"</span>
<span class="token punctuation">)</span>

<span class="token comment">// 定义Handle1结构体，</span>
<span class="token keyword">type</span> Handle1 <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">// Handle1 实现了http.Handler接口</span>
<span class="token comment">/*
源码：
type Handler interface &#123;
	ServeHTTP(ResponseWriter, *Request)
&#125;
*/</span>
<span class="token comment">// 实现了Handle1 的ServerHTTP方法，用于处理HTTP请求</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>h1 <span class="token operator">*</span>Handle1<span class="token punctuation">)</span> <span class="token function">ServeHTTP</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"这是handle1"</span><span class="token punctuation">)</span> <span class="token comment">// 向相应写入内容</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 定义类型 Handle2，同样实现了 http.Handler 接口</span>
<span class="token keyword">type</span> Handle2 <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">// 实现 Handle2 的 ServeHTTP 方法，用于处理 HTTP 请求</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>h2 <span class="token operator">*</span>Handle2<span class="token punctuation">)</span> <span class="token function">ServeHTTP</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"这是handle2"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>

<span class="token comment">// 定义一个函数 Hello，用于处理根路径的 HTTP 请求</span>
<span class="token keyword">func</span> <span class="token function">Hello</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"1"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>RemoteAddr<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"2"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Method<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"3"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Host<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"4"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>URL<span class="token punctuation">)</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"这是测试页面"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 定义一个函数 Test，用于处理 "/test" 路径的 HTTP 请求</span>
<span class="token keyword">func</span> <span class="token function">Test</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"testtesttest"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 创建Handle1和Handle2的实例</span>
    handle1 <span class="token operator">:=</span> Handle1<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
    handle2 <span class="token operator">:=</span> Handle2<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
    <span class="token comment">// 创建一个HTTP服务器配置</span>
    server <span class="token operator">:=</span> http<span class="token punctuation">.</span>Server<span class="token punctuation">&#123;</span>
        Addr<span class="token punctuation">:</span>    <span class="token string">"0.0.0.0:8085"</span><span class="token punctuation">,</span>
        Handler<span class="token punctuation">:</span> <span class="token boolean">nil</span><span class="token punctuation">,</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 注册Handle1和Handle2 为不同路径的处理器</span>
    http<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span><span class="token string">"/handle1"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>handle1<span class="token punctuation">)</span>
    http<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span><span class="token string">"/handle2"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>handle2<span class="token punctuation">)</span>
    <span class="token comment">// 注册函数 Hello为根路径的处理器</span>
    http<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> Hello<span class="token punctuation">)</span>
    <span class="token comment">// 启动HTTP服务器监听</span>
    server<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面的代码中，直接用<code>http.Handle()</code> 函数来指定多个处理器。Handle()函数的代码如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Handle</span><span class="token punctuation">(</span>pattern <span class="token builtin">string</span><span class="token punctuation">,</span> handler Handler<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span> DefaultServeMux<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>pattern<span class="token punctuation">,</span> handler<span class="token punctuation">)</span> <span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>可以看到在<code>http.Handle()</code> 函数中调用了<code>DefaultServeMux.Handle()</code> 方法来处理请求。服务器收到的每个请求都会调用对应多路复用器的<code>ServeHTTP()</code> 方法。该方法的代码如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>sh serverHandler<span class="token punctuation">)</span> <span class="token function">ServeHTTP</span><span class="token punctuation">(</span>rw ResponseWriter<span class="token punctuation">,</span> req <span class="token operator">*</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	handler <span class="token operator">:=</span> sh<span class="token punctuation">.</span>srv<span class="token punctuation">.</span>Handler
	<span class="token keyword">if</span> handler <span class="token operator">==</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
		handler <span class="token operator">=</span> DefaultServeMux
	<span class="token punctuation">&#125;</span>
	handler<span class="token punctuation">.</span><span class="token function">ServeHTTP</span><span class="token punctuation">(</span>rw<span class="token punctuation">,</span> req<span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在ServeMux对象的ServeHTTP()方法中，会根据URL查找我们注册的处理器，然后将请求交由它处理。</p>
<p>虽然默认的多路复用器用起来很方便，但是生产环境不建议使用。因为DefaultServeMux是一个全局变量，所有代码（包括第三方代码）都可以修改它。有些第三方代码会在DefaultServeMux中注册一些处理器，可能会与自己注册的处理器冲突。比较推荐的做法是自定义多路复用器。</p>
<p>自定义多路复用器直接调用<code>http.NewServeMux()</code> 函数即可。然后再新创建的多路复用器上注册处理器。</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go">mux <span class="token operator">:=</span> http<span class="token punctuation">.</span><span class="token function">NewServeMux</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span>hi<span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 定义一个函数 Hello，用于处理根路径的 HTTP 请求</span>
<span class="token keyword">func</span> <span class="token function">Hello</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"1"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>RemoteAddr<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"2"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Method<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"3"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Host<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"4"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>URL<span class="token punctuation">)</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"这是测试页面"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// 定义一个函数 Test，用于处理 "/test" 路径的 HTTP 请求</span>
<span class="token keyword">func</span> <span class="token function">Test</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"testtesttest"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">// 创建新的ServeMux（路由器）</span>
    mux <span class="token operator">:=</span> http<span class="token punctuation">.</span><span class="token function">NewServeMux</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> Hello<span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/test"</span><span class="token punctuation">,</span> Test<span class="token punctuation">)</span>
    <span class="token comment">// 创建一个HTTP服务器配置</span>
    server <span class="token operator">:=</span> http<span class="token punctuation">.</span>Server<span class="token punctuation">&#123;</span>
        Addr<span class="token punctuation">:</span>    <span class="token string">"0.0.0.0:8085"</span><span class="token punctuation">,</span> <span class="token comment">// 监听的地址和端口</span>
        Handler<span class="token punctuation">:</span> mux<span class="token punctuation">,</span>  <span class="token comment">// 使用自定义的ServeMux</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 启动HTTP服务器监听</span>
    <span class="token keyword">if</span> err <span class="token operator">:=</span> server<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p> 上面例子中与默认多路复用器的功能相同，都是启动一个HTTP服务器端。<strong>这里还创建了服务器对象Server。通过指定服务器的参数</strong>，可以创建定制化的服务器，如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 创建一个HTTP服务器配置</span>
server <span class="token operator">:=</span> http<span class="token punctuation">.</span>Server<span class="token punctuation">&#123;</span>
    Addr<span class="token punctuation">:</span>    <span class="token string">"0.0.0.0:8085"</span><span class="token punctuation">,</span>
    Handler<span class="token punctuation">:</span> mux<span class="token punctuation">,</span>
    ReadTimeout<span class="token punctuation">:</span> <span class="token number">10</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span>
    WriteTimeout<span class="token punctuation">:</span> <span class="token number">10</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面代码，创建了一个读超时和写超时都为10s的服务器，下面是源码中定义的一些相关服务器配置的参数：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">type</span> Server <span class="token keyword">struct</span> <span class="token punctuation">&#123;</span>
	<span class="token comment">// Addr optionally specifies the TCP address for the server to listen on,</span>
	<span class="token comment">// in the form "host:port". If empty, ":http" (port 80) is used.</span>
	<span class="token comment">// The service names are defined in RFC 6335 and assigned by IANA.</span>
	<span class="token comment">// See net.Dial for details of the address format.</span>
	Addr <span class="token builtin">string</span>

	Handler Handler <span class="token comment">// handler to invoke, http.DefaultServeMux if nil</span>

	<span class="token comment">// TLSConfig optionally provides a TLS configuration for use</span>
	<span class="token comment">// by ServeTLS and ListenAndServeTLS. Note that this value is</span>
	<span class="token comment">// cloned by ServeTLS and ListenAndServeTLS, so it's not</span>
	<span class="token comment">// possible to modify the configuration with methods like</span>
	<span class="token comment">// tls.Config.SetSessionTicketKeys. To use</span>
	<span class="token comment">// SetSessionTicketKeys, use Server.Serve with a TLS Listener</span>
	<span class="token comment">// instead.</span>
	TLSConfig <span class="token operator">*</span>tls<span class="token punctuation">.</span>Config

	<span class="token comment">// ReadTimeout is the maximum duration for reading the entire</span>
	<span class="token comment">// request, including the body. A zero or negative value means</span>
	<span class="token comment">// there will be no timeout.</span>
	<span class="token comment">//</span>
	<span class="token comment">// Because ReadTimeout does not let Handlers make per-request</span>
	<span class="token comment">// decisions on each request body's acceptable deadline or</span>
	<span class="token comment">// upload rate, most users will prefer to use</span>
	<span class="token comment">// ReadHeaderTimeout. It is valid to use them both.</span>
	ReadTimeout time<span class="token punctuation">.</span>Duration

	<span class="token comment">// ReadHeaderTimeout is the amount of time allowed to read</span>
	<span class="token comment">// request headers. The connection's read deadline is reset</span>
	<span class="token comment">// after reading the headers and the Handler can decide what</span>
	<span class="token comment">// is considered too slow for the body. If ReadHeaderTimeout</span>
	<span class="token comment">// is zero, the value of ReadTimeout is used. If both are</span>
	<span class="token comment">// zero, there is no timeout.</span>
	ReadHeaderTimeout time<span class="token punctuation">.</span>Duration

	<span class="token comment">// WriteTimeout is the maximum duration before timing out</span>
	<span class="token comment">// writes of the response. It is reset whenever a new</span>
	<span class="token comment">// request's header is read. Like ReadTimeout, it does not</span>
	<span class="token comment">// let Handlers make decisions on a per-request basis.</span>
	<span class="token comment">// A zero or negative value means there will be no timeout.</span>
	WriteTimeout time<span class="token punctuation">.</span>Duration

	<span class="token comment">// IdleTimeout is the maximum amount of time to wait for the</span>
	<span class="token comment">// next request when keep-alives are enabled. If IdleTimeout</span>
	<span class="token comment">// is zero, the value of ReadTimeout is used. If both are</span>
	<span class="token comment">// zero, there is no timeout.</span>
	IdleTimeout time<span class="token punctuation">.</span>Duration

	<span class="token comment">// MaxHeaderBytes controls the maximum number of bytes the</span>
	<span class="token comment">// server will read parsing the request header's keys and</span>
	<span class="token comment">// values, including the request line. It does not limit the</span>
	<span class="token comment">// size of the request body.</span>
	<span class="token comment">// If zero, DefaultMaxHeaderBytes is used.</span>
	MaxHeaderBytes <span class="token builtin">int</span>

	<span class="token comment">// TLSNextProto optionally specifies a function to take over</span>
	<span class="token comment">// ownership of the provided TLS connection when an ALPN</span>
	<span class="token comment">// protocol upgrade has occurred. The map key is the protocol</span>
	<span class="token comment">// name negotiated. The Handler argument should be used to</span>
	<span class="token comment">// handle HTTP requests and will initialize the Request's TLS</span>
	<span class="token comment">// and RemoteAddr if not already set. The connection is</span>
	<span class="token comment">// automatically closed when the function returns.</span>
	<span class="token comment">// If TLSNextProto is not nil, HTTP/2 support is not enabled</span>
	<span class="token comment">// automatically.</span>
	TLSNextProto <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span><span class="token keyword">func</span><span class="token punctuation">(</span><span class="token operator">*</span>Server<span class="token punctuation">,</span> <span class="token operator">*</span>tls<span class="token punctuation">.</span>Conn<span class="token punctuation">,</span> Handler<span class="token punctuation">)</span>

	<span class="token comment">// ConnState specifies an optional callback function that is</span>
	<span class="token comment">// called when a client connection changes state. See the</span>
	<span class="token comment">// ConnState type and associated constants for details.</span>
	ConnState <span class="token keyword">func</span><span class="token punctuation">(</span>net<span class="token punctuation">.</span>Conn<span class="token punctuation">,</span> ConnState<span class="token punctuation">)</span>

	<span class="token comment">// ErrorLog specifies an optional logger for errors accepting</span>
	<span class="token comment">// connections, unexpected behavior from handlers, and</span>
	<span class="token comment">// underlying FileSystem errors.</span>
	<span class="token comment">// If nil, logging is done via the log package's standard logger.</span>
	ErrorLog <span class="token operator">*</span>log<span class="token punctuation">.</span>Logger

	<span class="token comment">// BaseContext optionally specifies a function that returns</span>
	<span class="token comment">// the base context for incoming requests on this server.</span>
	<span class="token comment">// The provided Listener is the specific Listener that's</span>
	<span class="token comment">// about to start accepting requests.</span>
	<span class="token comment">// If BaseContext is nil, the default is context.Background().</span>
	<span class="token comment">// If non-nil, it must return a non-nil context.</span>
	BaseContext <span class="token keyword">func</span><span class="token punctuation">(</span>net<span class="token punctuation">.</span>Listener<span class="token punctuation">)</span> context<span class="token punctuation">.</span>Context

	<span class="token comment">// ConnContext optionally specifies a function that modifies</span>
	<span class="token comment">// the context used for a new connection c. The provided ctx</span>
	<span class="token comment">// is derived from the base context and has a ServerContextKey</span>
	<span class="token comment">// value.</span>
	ConnContext <span class="token keyword">func</span><span class="token punctuation">(</span>ctx context<span class="token punctuation">.</span>Context<span class="token punctuation">,</span> c net<span class="token punctuation">.</span>Conn<span class="token punctuation">)</span> context<span class="token punctuation">.</span>Context

	inShutdown atomicBool <span class="token comment">// true when server is in shutdown</span>

	disableKeepAlives <span class="token builtin">int32</span>     <span class="token comment">// accessed atomically.</span>
	nextProtoOnce     sync<span class="token punctuation">.</span>Once <span class="token comment">// guards setupHTTP2_* init</span>
	nextProtoErr      <span class="token builtin">error</span>     <span class="token comment">// result of http2.ConfigureServer if used</span>

	mu         sync<span class="token punctuation">.</span>Mutex
	listeners  <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token operator">*</span>net<span class="token punctuation">.</span>Listener<span class="token punctuation">]</span><span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
	activeConn <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token operator">*</span>conn<span class="token punctuation">]</span><span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
	doneChan   <span class="token keyword">chan</span> <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
	onShutdown <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token keyword">func</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

	listenerGroup sync<span class="token punctuation">.</span>WaitGroup
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ol>
<li><code>Addr</code>: 指定服务器监听的 TCP 地址和端口。如果留空，则默认使用 <code>&quot;:http&quot;</code>（端口 80）。</li>
<li><code>Handler</code>: 指定用于处理 HTTP 请求的处理器。如果为 <code>nil</code>，则使用 <code>http.DefaultServeMux</code>。</li>
<li><code>TLSConfig</code>: 提供 TLS 配置，用于在使用 <code>ServeTLS</code> 和 <code>ListenAndServeTLS</code> 时使用。注意，该值会被 <code>ServeTLS</code> 和 <code>ListenAndServeTLS</code> 克隆，因此无法通过诸如 <code>tls.Config.SetSessionTicketKeys</code> 之类的方法修改配置。</li>
<li><code>ReadTimeout</code>: 读取整个请求（包括请求体）的最大持续时间。零或负值表示没有超时。</li>
<li><code>ReadHeaderTimeout</code>: 读取请求头的最大持续时间。在读取完请求头后，连接的读取截止时间会重置，处理程序可以决定请求体的速度。如果为零，则使用 <code>ReadTimeout</code> 的值。如果两者都为零，则没有超时。</li>
<li><code>WriteTimeout</code>: 写入响应的最大持续时间。在读取新请求的头部时，会重置这个时间。与 <code>ReadTimeout</code> 类似，它不允许处理程序对每个请求进行超时设置。零或负值表示没有超时。</li>
<li><code>IdleTimeout</code>: 在启用了 Keep-Alive 时等待下一个请求的最大持续时间。如果 <code>IdleTimeout</code> 为零，则使用 <code>ReadTimeout</code> 的值。如果两者都为零，则没有超时。</li>
<li><code>MaxHeaderBytes</code>: 控制服务器解析请求头键和值的最大字节数，包括请求行。不限制请求体的大小。如果为零，则使用 <code>DefaultMaxHeaderBytes</code>。</li>
<li><code>TLSNextProto</code>: 可选地指定一个函数，用于在 ALPN 协议升级发生时接管提供的 TLS 连接。映射键是协议名称。处理程序参数用于处理 HTTP 请求，并将初始化请求的 TLS 和 RemoteAddr（如果尚未设置）。函数返回时，连接会自动关闭。如果 <code>TLSNextProto</code> 不为 <code>nil</code>，则不会自动启用 HTTP&#x2F;2 支持。</li>
<li><code>ConnState</code>: 指定一个可选的回调函数，在客户端连接状态发生变化时调用。</li>
<li><code>ErrorLog</code>: 指定一个可选的错误记录器，用于记录连接接受错误、处理程序的意外行为以及底层文件系统错误。如果为 <code>nil</code>，则使用 <code>log</code> 包的标准记录器。</li>
<li><code>BaseContext</code>: 可选地指定一个函数，用于为该服务器上的传入请求返回基本上下文。</li>
<li><code>ConnContext</code>: 可选地指定一个函数，用于修改新连接的上下文。提供的 <code>ctx</code> 是从基本上下文派生的，具有 <code>ServerContextKey</code> 值。</li>
<li><code>inShutdown</code>: 标志，当服务器正在关闭时为 <code>true</code>。</li>
<li><code>disableKeepAlives</code>: 禁用 Keep-Alive 的标志，通过原子方式访问。</li>
<li><code>nextProtoOnce</code>: 用于保护 <code>setupHTTP2_*</code> 初始化的 <code>sync.Once</code> 互斥锁。</li>
<li><code>nextProtoErr</code>: 如果使用了 <code>http2.ConfigureServer</code>，则为该函数的结果，表示 HTTP&#x2F;2 的初始化结果。</li>
<li><code>mu</code>: 用于保护以下字段的 <code>sync.Mutex</code> 互斥锁。</li>
<li><code>listeners</code>: 跟踪服务器正在监听的网络连接。</li>
<li><code>activeConn</code>: 跟踪服务器中当前活动的连接。</li>
<li><code>doneChan</code>: 在服务器关闭时发送信号的通道。</li>
<li><code>onShutdown</code>: 在服务器关闭时执行的回调函数列表。</li>
<li><code>listenerGroup</code>: 等待活动监听器完成的 <code>sync.WaitGroup</code>。</li>
</ol>
<p>*<em>简单总结：ServeMux 实现了</em><em><strong>http.Handler</strong></em><em>接口的</em><em>*<em>ServeHTTP(ResponseWriter,*Request)<strong><strong>方法。在创建Server时，如果设置Handler为空，则使用默认的</strong></strong>DefaultServeMux</em>*</em><em>作为默认的处理器，而</em><em><strong>DefaultServeMux</strong></em><em>是</em><em><strong>ServeMux</strong></em><em>的一个全局变量。</em>*</p>
<p>####### <strong>2、ServeMux的URL路由匹配</strong><br>实际应用中，一个web服务器会有很多的URL绑定，不同的URL对应不同的处理器。</p>
<p>如果现在绑定了3个URL，分别是&#x2F;、&#x2F;user、&#x2F;role</p>
<ul>
<li>如果请求的URL为&#x2F;，则调用&#x2F;对应的处理器。</li>
<li>如果请求的URL为&#x2F;user，则调用&#x2F;user对应的处理器。</li>
<li>如果请求的URL为&#x2F;role，则调用&#x2F;role对应的处理器。</li>
</ul>
<blockquote>
<p>如果注册的URL不是以／结尾的,则它只能精确匹配请求的URL。反之,即使请求的URL只有前缀与被绑定的URL相同,则ServeMux也认为它们是匹配的。例如′如果请求的URL为&#x2F;user&#x2F; 则不能匹配到&#x2F;user因为&#x2F;user不以&#x2F;结尾，必须精确匹配。如果我们绑定的URL为&#x2F;user&#x2F;，则当服务器找不到与&#x2F;user&#x2F;others完全匹配的处理器时，就会退而求其次，开始寻找能够与&#x2F;user&#x2F;匹配的处理器。</p>
</blockquote>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">indexHandler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"欢迎来到Go Web首页！处理器为：indexHandler"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">userHandler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"欢迎来到Go Web用户页！处理器为：userHandler"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">roleHandler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"欢迎来到Go Web权限页！处理器为：roleHandler"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    mux <span class="token operator">:=</span> http<span class="token punctuation">.</span><span class="token function">NewServeMux</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> indexHandler<span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/user"</span><span class="token punctuation">,</span> userHandler<span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/role/web"</span><span class="token punctuation">,</span> roleHandler<span class="token punctuation">)</span>
    <span class="token comment">// 创建一个HTTP服务器配置</span>
    server <span class="token operator">:=</span> http<span class="token punctuation">.</span>Server<span class="token punctuation">&#123;</span>
        Addr<span class="token punctuation">:</span>         <span class="token string">"0.0.0.0:8085"</span><span class="token punctuation">,</span>
        Handler<span class="token punctuation">:</span>      mux<span class="token punctuation">,</span>
        ReadTimeout<span class="token punctuation">:</span>  <span class="token number">10</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span>
        WriteTimeout<span class="token punctuation">:</span> <span class="token number">10</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 启动HTTP服务器监听</span>
    <span class="token keyword">if</span> err <span class="token operator">:=</span> server<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p><img src="/images/7S0BLT5M_pHphocDPiOZMGnDg2nKU8_qoATFiQZg66E.png" alt="image"></p>
<p><img src="/images/xLBNIVYLG-AcXxWFv1hmKTRmdzwGiXmMTF_dRmoz-NQ.png" alt="image"></p>
<p>输入<a target="_blank" rel="noopener" href="http://127.0.0.1:8085/role/%EF%BC%8C%E5%B0%86%E8%BF%94%E5%9B%9E%E9%A6%96%E9%A1%B5%E7%9A%84%E5%A4%84%E7%90%86%E5%99%A8">http://127.0.0.1:8085/role/，将返回首页的处理器</a>:indexHandler，因为绑定的&#x2F;role需要精确匹配，而请求的&#x2F;role&#x2F;不能与之精确匹配所以向上查找到&#x2F;</p>
<p>处理器和处理器函数都可以进行URL路由匹配。通常情况下，可以使用处理器和处理器函数中的一种或同时使用两者，</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// 定义类型 Handle2，同样实现了 http.Handler 接口</span>
<span class="token keyword">type</span> Handle2 <span class="token keyword">struct</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>

<span class="token comment">// 实现 Handle2 的 ServeHTTP 方法，用于处理 HTTP 请求</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>h2 <span class="token operator">*</span>Handle2<span class="token punctuation">)</span> <span class="token function">ServeHTTP</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"这是handle2"</span><span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>

<span class="token comment">// 定义一个函数 Hello，用于处理根路径的 HTTP 请求</span>
<span class="token keyword">func</span> <span class="token function">Hello</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"1"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>RemoteAddr<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"2"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Method<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"3"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>Host<span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"4"</span><span class="token punctuation">,</span> r<span class="token punctuation">.</span>URL<span class="token punctuation">)</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"这是测试页面"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token keyword">func</span> <span class="token function">indexHandler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"欢迎来到Go Web首页！处理器为：indexHandler"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">userHandler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"欢迎来到Go Web用户页！处理器为：userHandler"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">roleHandler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    fmt<span class="token punctuation">.</span><span class="token function">Fprintf</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> <span class="token string">"欢迎来到Go Web权限页！处理器为：roleHandler"</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    handler2 <span class="token operator">:=</span> Handle2<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
    mux <span class="token operator">:=</span> http<span class="token punctuation">.</span><span class="token function">NewServeMux</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> indexHandler<span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/user"</span><span class="token punctuation">,</span> userHandler<span class="token punctuation">)</span>
    mux<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/role/web"</span><span class="token punctuation">,</span> roleHandler<span class="token punctuation">)</span>
    <span class="token comment">// 注册处理器</span>
    mux<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span><span class="token string">"/test/"</span><span class="token punctuation">,</span> <span class="token operator">&amp;</span>handler2<span class="token punctuation">)</span>
    <span class="token comment">// 创建一个HTTP服务器配置</span>
    server <span class="token operator">:=</span> http<span class="token punctuation">.</span>Server<span class="token punctuation">&#123;</span>
        Addr<span class="token punctuation">:</span>         <span class="token string">"0.0.0.0:8085"</span><span class="token punctuation">,</span>
        Handler<span class="token punctuation">:</span>      mux<span class="token punctuation">,</span>
        ReadTimeout<span class="token punctuation">:</span>  <span class="token number">10</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span>
        WriteTimeout<span class="token punctuation">:</span> <span class="token number">10</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">,</span>
    <span class="token punctuation">&#125;</span>
    <span class="token comment">// 启动HTTP服务器监听</span>
    <span class="token keyword">if</span> err <span class="token operator">:=</span> server<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">&#123;</span>
        log<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span>

<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>####### <strong>3、HttpRouter简介</strong><br>ServeMux一个缺陷是：无法使用变量实现URL模式匹配。而HttpRouter则可以。HttpRouter是一个高性能、可扩展的第三方HTTP路由包。HttpRouter包弥补了net&#x2F;http 包中默认路由不足的问题</p>
<p>（1）、安装HttpRouter</p>
<p><a target="_blank" rel="noopener" href="https://github.com/julienschmidt/httprouter">https://github.com/julienschmidt/httprouter</a></p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">go</span> get <span class="token operator">-</span>u github<span class="token punctuation">.</span>com<span class="token operator">/</span>julienschmidt<span class="token operator">/</span>httprouter<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
<p>(2)、HttpRouter使用方法如下：首先使用<code>httprouter.New()</code>函数生成了一个*Router 路由对象，然后使用**GET()*<em>方法注册一个适配&#x2F;路径的index函数，最后将</em>Router对象作为参数传给<code>ListenAndServe()</code>函数即可启动HTTP服务</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Index</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">,</span> <span class="token boolean">_</span> httprouter<span class="token punctuation">.</span>Params<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"首页Index"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>

    router <span class="token operator">:=</span> httprouter<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    router<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">,</span> Index<span class="token punctuation">)</span>
    http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">":8080"</span><span class="token punctuation">,</span> router<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>HttpRouter包为常用的HTTP方法提供了快捷的使用方式。常用请求方法定义如下：</p>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token comment">// GET is a shortcut for router.Handle(http.MethodGet, path, handle)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>Router<span class="token punctuation">)</span> <span class="token function">GET</span><span class="token punctuation">(</span>path <span class="token builtin">string</span><span class="token punctuation">,</span> handle Handle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	r<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>MethodGet<span class="token punctuation">,</span> path<span class="token punctuation">,</span> handle<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// HEAD is a shortcut for router.Handle(http.MethodHead, path, handle)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>Router<span class="token punctuation">)</span> <span class="token function">HEAD</span><span class="token punctuation">(</span>path <span class="token builtin">string</span><span class="token punctuation">,</span> handle Handle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	r<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>MethodHead<span class="token punctuation">,</span> path<span class="token punctuation">,</span> handle<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// OPTIONS is a shortcut for router.Handle(http.MethodOptions, path, handle)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>Router<span class="token punctuation">)</span> <span class="token function">OPTIONS</span><span class="token punctuation">(</span>path <span class="token builtin">string</span><span class="token punctuation">,</span> handle Handle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	r<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>MethodOptions<span class="token punctuation">,</span> path<span class="token punctuation">,</span> handle<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// POST is a shortcut for router.Handle(http.MethodPost, path, handle)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>Router<span class="token punctuation">)</span> <span class="token function">POST</span><span class="token punctuation">(</span>path <span class="token builtin">string</span><span class="token punctuation">,</span> handle Handle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	r<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>MethodPost<span class="token punctuation">,</span> path<span class="token punctuation">,</span> handle<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// PUT is a shortcut for router.Handle(http.MethodPut, path, handle)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>Router<span class="token punctuation">)</span> <span class="token function">PUT</span><span class="token punctuation">(</span>path <span class="token builtin">string</span><span class="token punctuation">,</span> handle Handle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	r<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>MethodPut<span class="token punctuation">,</span> path<span class="token punctuation">,</span> handle<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// PATCH is a shortcut for router.Handle(http.MethodPatch, path, handle)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>Router<span class="token punctuation">)</span> <span class="token function">PATCH</span><span class="token punctuation">(</span>path <span class="token builtin">string</span><span class="token punctuation">,</span> handle Handle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	r<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>MethodPatch<span class="token punctuation">,</span> path<span class="token punctuation">,</span> handle<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>

<span class="token comment">// DELETE is a shortcut for router.Handle(http.MethodDelete, path, handle)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>r <span class="token operator">*</span>Router<span class="token punctuation">)</span> <span class="token function">DELETE</span><span class="token punctuation">(</span>path <span class="token builtin">string</span><span class="token punctuation">,</span> handle Handle<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	r<span class="token punctuation">.</span><span class="token function">Handle</span><span class="token punctuation">(</span>http<span class="token punctuation">.</span>MethodDelete<span class="token punctuation">,</span> path<span class="token punctuation">,</span> handle<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>


<p>HttpRouter包提供了对命名参数的支持，可以很方便的开发RestfulAPI。比如，设计example&#x2F;user&#x2F;dujie这样一个URL，可以查看dujie这个用户的信息。如果要查看其他用户（比如zhangsan）的信息，则只需要访问example&#x2F;user&#x2F;zhangsan</p>
<p>在HttpRouter包中对URL使用两种匹配模式：</p>
<ol>
<li>形如&#x2F;user&#x2F;:name 的精确匹配</li>
<li>形如&#x2F;user&#x2F;*name 的匹配所有的模式</li>
</ol>
<pre class="line-numbers language-go" data-language="go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    router <span class="token operator">:=</span> httprouter<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    router<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/default"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>writer http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> request <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">,</span> params httprouter<span class="token punctuation">.</span>Params<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        writer<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"default get"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    router<span class="token punctuation">.</span><span class="token function">POST</span><span class="token punctuation">(</span><span class="token string">"/default"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>writer http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> request <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">,</span> params httprouter<span class="token punctuation">.</span>Params<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        writer<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"default post"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    <span class="token comment">// 精确匹配</span>
    <span class="token comment">//router.GET("/user/zhangsan", func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) &#123;</span>
    <span class="token comment">//    fmt.Println(params)</span>
    <span class="token comment">//    // fmt.Println(request.URL.Query().Get("name"))</span>
    <span class="token comment">//    writer.Write([]byte("user name:" + params.ByName("name")))</span>
    <span class="token comment">//&#125;)</span>
    router<span class="token punctuation">.</span><span class="token function">GET</span><span class="token punctuation">(</span><span class="token string">"/user/*name"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>writer http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> request <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">,</span> params httprouter<span class="token punctuation">.</span>Params<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>params<span class="token punctuation">)</span>
        rawName <span class="token operator">:=</span> params<span class="token punctuation">.</span><span class="token function">ByName</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span>
        <span class="token comment">// 去掉params对应name 前面的/</span>
        name <span class="token operator">:=</span> strings<span class="token punctuation">.</span><span class="token function">TrimLeft</span><span class="token punctuation">(</span>rawName<span class="token punctuation">,</span> <span class="token string">"/"</span><span class="token punctuation">)</span>
        fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>name<span class="token punctuation">)</span>
        writer<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"user name:"</span> <span class="token operator">+</span> params<span class="token punctuation">.</span><span class="token function">ByName</span><span class="token punctuation">(</span><span class="token string">"name"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
    http<span class="token punctuation">.</span><span class="token function">ListenAndServe</span><span class="token punctuation">(</span><span class="token string">":8080"</span><span class="token punctuation">,</span> router<span class="token punctuation">)</span>

<span class="token punctuation">&#125;</span>
<span class="token comment">// params的值： "user/*names" * 后面的names对应 params中的names</span>
<span class="token punctuation">[</span><span class="token punctuation">&#123;</span>names <span class="token operator">/</span>张三<span class="token punctuation">&#125;</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>






























































</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love">J.</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://dycloudnavite.love/2023/06/04/ServeMux%E3%80%81httprouter/">http://dycloudnavite.love/2023/06/04/ServeMux%E3%80%81httprouter/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://dycloudnavite.love" target="_blank">J.のblog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/dujie5416/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">云原生</a><a class="post-meta__tags" href="/dujie5416/tags/golang/">golang</a></div><div class="post_share"><div class="addthis_inline_share_toolbox"></div><script src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5d034d84b42927bf" async="async"></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/dujie5416/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/dujie5416/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src="/dujie5416/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/"><img class="prev-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Gin框架</div></div></a></div><div class="next-post pull-right"><a href="/dujie5416/2023/06/01/Sync%E5%8C%85%E5%AE%9E%E7%8E%B0%E5%B9%B6%E5%8F%91/"><img class="next-cover" src="/dujie5416/img/golang.png" onerror="onerror=null;src='/dujie5416/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Sync包实现并发</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/dujie5416/2023/05/20/Channel%E9%80%9A%E9%81%93/" title="Channel通道"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-20</div><div class="title">Channel通道</div></div></a></div><div><a href="/dujie5416/2023/05/06/Golang%E4%B8%AD%E7%9A%84GORM/" title="Golang GORM使用"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-06</div><div class="title">Golang GORM使用</div></div></a></div><div><a href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-06-23</div><div class="title">Gin框架</div></div></a></div><div><a href="/dujie5416/2023/05/15/Golang%E5%8D%8F%E7%A8%8B/" title="Golang协程"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-05-15</div><div class="title">Golang协程</div></div></a></div><div><a href="/dujie5416/2023/04/17/Golang%E5%8F%98%E9%87%8F%E9%80%83%E9%80%B8%E2%80%94%E2%80%94%E5%A0%86%E3%80%81%E6%A0%88/" title="Golang变量逃逸————堆、栈"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-04-17</div><div class="title">Golang变量逃逸————堆、栈</div></div></a></div><div><a href="/dujie5416/2023/02/13/Golang%E5%AD%97%E7%AC%A6%E4%B8%B2string/" title="Golang字符串"><img class="cover" src="/dujie5416/img/golang.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-13</div><div class="title">Golang字符串</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="lv-container" data-id="city" data-uid="MTAyMC81Njk5OS8zMzQ2Mw=="></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/dujie5416/img/touxiang.png" onerror="this.onerror=null;this.src='/dujie5416/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">J.</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/dujie5416/archives/"><div class="headline">文章</div><div class="length-num">73</div></a><a href="/dujie5416/tags/"><div class="headline">标签</div><div class="length-num">17</div></a><a href="/dujie5416/categories/"><div class="headline">分类</div><div class="length-num">11</div></a></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#ServeMux%E3%80%81httprouter"><span class="toc-number">1.</span> <span class="toc-text">ServeMux、httprouter</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84goWeb%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-number">1.0.1.</span> <span class="toc-text">一、创建一个简单的goWeb服务器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E6%8E%A5%E5%8F%97%E8%AF%B7%E6%B1%82"><span class="toc-number">1.0.2.</span> <span class="toc-text">二、接受请求</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#2-1%E3%80%81ServeMux%E5%92%8CDefaultServeMux"><span class="toc-number">1.0.2.0.1.</span> <span class="toc-text">2.1、ServeMux和DefaultServeMux</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="vue3左侧菜单隐藏某选项"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/29/%E6%A0%B9%E6%8D%AErouter%E6%98%BE%E7%A4%BA%E5%B7%A6%E4%BE%A7%E8%8F%9C%E5%8D%95%E6%A0%8F%E9%9A%90%E8%97%8F%E6%9F%90%E4%B8%AA%E8%8F%9C%E5%8D%95%E9%80%89%E9%A1%B9/" title="vue3左侧菜单隐藏某选项">vue3左侧菜单隐藏某选项</a><time datetime="2023-07-29T06:32:00.000Z" title="发表于 2023-07-29 14:32:00">2023-07-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Vue状态管理"/></a><div class="content"><a class="title" href="/dujie5416/2023/07/13/Vue%E7%8A%B6%E6%80%81%E7%AE%A1%E7%90%86/" title="Vue状态管理">Vue状态管理</a><time datetime="2023-07-13T09:29:00.000Z" title="发表于 2023-07-13 17:29:00">2023-07-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="基于IOC解决对象依赖问题"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/27/%E5%9F%BA%E4%BA%8EIOC%E8%A7%A3%E5%86%B3%E5%AF%B9%E8%B1%A1%E4%BE%9D%E8%B5%96%E9%97%AE%E9%A2%98/" title="基于IOC解决对象依赖问题">基于IOC解决对象依赖问题</a><time datetime="2023-06-27T03:32:00.000Z" title="发表于 2023-06-27 11:32:00">2023-06-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="Gin框架"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/23/Gin%E6%A1%86%E6%9E%B6/" title="Gin框架">Gin框架</a><time datetime="2023-06-23T06:32:00.000Z" title="发表于 2023-06-23 14:32:00">2023-06-23</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter"><img src="/dujie5416/img/golang.png" onerror="this.onerror=null;this.src='/dujie5416/img/404.jpg'" alt="ServeMux、httprouter"/></a><div class="content"><a class="title" href="/dujie5416/2023/06/04/ServeMux%E3%80%81httprouter/" title="ServeMux、httprouter">ServeMux、httprouter</a><time datetime="2023-06-04T03:32:00.000Z" title="发表于 2023-06-04 11:32:00">2023-06-04</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/dujie5416/img/longzhu.png')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2024  <i id="heartbeat" class="fa fas fa-heartbeat"></i> J.</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a><a href="http://beian.miit.gov.cn/"  style="color:#f72b07" target="_blank">京ICP备2022023567号</a></div></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/gh/HCLonely/images@master/others/heartbeat.min.css"></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="search-wrap"><div id="algolia-search-input"></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-info"><div class="algolia-stats"></div><div class="algolia-poweredBy"></div></div></div></div></div><div id="search-mask"></div></div><div id="rightMenu"><div class="rightMenu-group rightMenu-small"><div class="rightMenu-item" id="menu-backward"><i class="fa-solid fa-arrow-left"></i></div><div class="rightMenu-item" id="menu-forward"><i class="fa-solid fa-arrow-right"></i></div><div class="rightMenu-item" id="menu-refresh"><i class="fa-solid fa-arrow-rotate-right"></i></div><div class="rightMenu-item" id="menu-home"><i class="fa-solid fa-house"></i></div></div><div class="rightMenu-group rightMenu-line rightMenuOther"><a class="rightMenu-item menu-link" href="/archives/"><i class="fa-solid fa-archive"></i><span>文章归档</span></a><a class="rightMenu-item menu-link" href="/categories/"><i class="fa-solid fa-folder-open"></i><span>文章分类</span></a><a class="rightMenu-item menu-link" href="/tags/"><i class="fa-solid fa-tags"></i><span>文章标签</span></a></div><div class="rightMenu-group rightMenu-line rightMenuNormal"><a class="rightMenu-item menu-link" id="menu-radompage" href="/random/index.html"><i class="fa-solid fa-shoe-prints"></i><span>随便逛逛</span></a><div class="rightMenu-item" id="menu-translate"><i class="fa-solid fa-earth-asia"></i><span>繁简切换</span></div><div class="rightMenu-item" id="menu-darkmode"><i class="fa-solid fa-moon"></i><span>切换模式</span></div></div></div><div id="rightmenu-mask"></div><div><script src="/dujie5416/js/utils.js"></script><script src="/dujie5416/js/main.js"></script><script src="/dujie5416/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/algoliasearch/dist/algoliasearch-lite.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instantsearch.js/dist/instantsearch.production.min.js"></script><script src="/dujie5416/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>function loadLivere () {
  if (typeof LivereTower === 'object') {
    window.LivereTower.init()
  }
  else {
    (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
    })(document, 'script');
  }
}

if ('Livere' === 'Livere' || !false) {
  if (false) btf.loadComment(document.getElementById('lv-container'), loadLivere)
  else loadLivere()
}
else {
  function loadOtherComment () {
    loadLivere()
  }
}</script></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script><script data-pjax defer src="https://npm.elemecdn.com/tzy-blog/lib/js/theme/chocolate.js"></script><canvas id="universe"></canvas><script defer src="/js/universe.js"></script><script defer data-pjax src="/js/rightMenu.js"></script><div class="aplayer no-destroy" data-id="7427714271" data-server="netease" data-type="playlist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-lrctype="1" data-preload="none" data-autoplay="true" muted></div><script id="click-show-text" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/click-show-text.min.js" data-mobile="false" data-text="I,LOVE,YOU" data-fontsize="15px" data-random="false" async="async"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/metingjs/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["meta[property=\"og:image\"]","meta[property=\"og:title\"]","meta[property=\"og:url\"]","head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><!-- hexo injector body_end start --><script data-pjax>
  function butterfly_clock_anzhiyu_injector_config(){
    var parent_div_git = document.getElementsByClassName('sticky_layout')[0];
    var item_html = '<div class="card-widget card-clock"><div class="card-glass"><div class="card-background"><div class="card-content"><div id="hexo_electric_clock"><img class="entered loading" id="card-clock-loading" src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/loading.gif" style="height: 120px; width: 100%;" data-ll-status="loading"/></div></div></div></div></div>';
    console.log('已挂载butterfly_clock_anzhiyu')
    if(parent_div_git) {
      parent_div_git.insertAdjacentHTML("afterbegin",item_html)
    }
  }
  var elist = 'null'.split(',');
  var cpage = location.pathname;
  var epage = 'all';
  var qweather_key = '56289903f0d448dfbe8262dba0175f70';
  var gaud_map_key = '01603f2b2d08d0e947bb101e9d9b148b';
  var baidu_ak_key = 'undefined';
  var flag = 0;
  var clock_rectangle = '112.982279,28.19409';
  var clock_default_rectangle_enable = 'false';

  for (var i=0;i<elist.length;i++){
    if (cpage.includes(elist[i])){
      flag++;
    }
  }

  if ((epage ==='all')&&(flag == 0)){
    butterfly_clock_anzhiyu_injector_config();
  }
  else if (epage === cpage){
    butterfly_clock_anzhiyu_injector_config();
  }
  </script><script src="https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0"></script><script data-pjax src="https://cdn.cbd.int/hexo-butterfly-clock-anzhiyu/lib/clock.min.js"></script><!-- hexo injector body_end end --><script src="/dujie5416/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"tagMode":false,"debug":false,"model":{"jsonPath":"/dujie5416/live2dw/assets/tororo.model.json"},"display":{"position":"right","width":150,"height":350,"hOffset":20,"vOffset":-20},"mobile":{"show":false},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/"});</script><script async>window.onload=function(){var a=document.createElement('script'),b=document.getElementsByTagName('script')[0];a.type='text/javascript',a.async=!0,a.src='/sw-register.js?v='+Date.now(),b.parentNode.insertBefore(a,b)};</script></body></html>